package middleware

import (
	"github.com/pkg/errors"
	"strconv"
	"time"
	"web_framework/config"
	"web_framework/model"
	"web_framework/pkg/constvar"
	"web_framework/pkg/e"
	"web_framework/pkg/errno"
	"web_framework/storage"
)

// 校验用户token
func CheckUserToken(uid int, token string) (error, bool) {

	if uid < 1 {
		return errno.ParamsEmpty, false
	}

	tokenKey := constvar.RedisUserToken + strconv.Itoa(uid)
	find, err := storage.RedisZCard(tokenKey)
	if err == nil && find > 1 {
		return nil, true
	}

	// Redis找不到去搜索DB
	find, err = storage.GetUserTokenByUidAndToken(config.C.DB.DB, uid, token)
	if find > 0 {
		return nil, true
	}

	return errno.ErrDatabase, false
}

// 用户token相关
func AddUserToken(uid, client int, registerRationId string) (err error, token string) {

	if uid < 1 {
		return errors.New(errno.ParamsEmpty.Message + "{ uid }"), ""
	}

	// 随机生成Token
	token = e.Md5Str(strconv.FormatInt(e.MicroTime(),10) + strconv.Itoa(e.RandInt(1000, 9999)))

	var userToken model.UserToken
	userToken.Uid = uid
	userToken.Client = client
	userToken.Token = token
	userToken.RegisterRationId = registerRationId

	err = storage.AddUserToken(config.C.DB.DB, &userToken)
	if err != nil {
		return err, ""
	}

	// 写入redis
	tokenKey := constvar.RedisUserToken + strconv.Itoa(uid)
	storage.RedisZAdd(tokenKey,token,time.Now().Unix())

	// 检测是否已经用户满了10个token
	count, err := storage.GetUserTokenCount(config.C.DB.DB, uid)
	if err != nil {
		return err, ""
	}

	// 删掉库和redis 里面多的token
	if count > constvar.UserTokenLimit {
		deleteToken, err := storage.GetUserToken(config.C.DB.DB, uid)
		if err != nil {
			return err, ""
		}else {
			err = storage.DeleteUserToken(config.C.DB.DB, uid, 1)
			if err != nil {
				return err, ""
			}
		}
		checkToken,_ := storage.RedisZRange(tokenKey, 0, 0)
		if len(checkToken) > 0 && checkToken[0] == deleteToken {
			re, err := storage.RedisZRem(tokenKey, deleteToken)
			if re == false {
				return err, ""
			}
		}
	}

	return nil, token
}